﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;//显示动画效果需要
using System.Drawing.Imaging;//保存位图需要
using System.Net;
using System.Net.Sockets;
using System.IO;
using CustomXML;


namespace NetChatInterface
{
    public partial class SessionForm : Form
    {
        //**********************************************
        
        IntPtr hMainFormHandle;//储存主窗口的句柄

        bool PaletteIsOpen = false; 
        SolidBrush drawBrush = new SolidBrush(Color.Black);
        SolidBrush creatTheMemoryImagebrush = new SolidBrush(Color.White);
        Pen drawPen = new Pen(Color.Black);
        Pen eraserPen = new Pen(Color.White);
        Point startPoint = new Point();
        Point endPoint = new Point();
        enum drawTools { Pen = 0, MouseMove, Line, Rectangle, Ellipse, SolidEllipse,MultiEllipse,None };  
        drawTools drawtool = drawTools.None;
        Image theMemoryImage;
        Image openFileImage;
        Graphics theMemoryGraphics;
        Graphics mainPanelGraphics;
        bool isdrawing = false;
        OpenFileDialog openFileDialog = new OpenFileDialog();

        //File Send
        TcpClient _tc;
        NetworkStream _ns;
        byte[] _sendBuf = new byte[1024];
        public string DestinationIP;//目的地IP地址
        public string FilePath;//储存要发送的文件的路径
        public string filename;//储存所要发送的文件的名字
        public string FileStoreDirectory;//储存要保存的文件的文件夹路径
        //BrowseSend
        FileBrowseTransmission fbt = new FileBrowseTransmission();
        //**********************************************  

        
        protected void PaintPic(int X,int Y)
        {
            if (UsePenButton.Checked)
            {
                switch (drawtool)
                {
                    case drawTools.None:
                        break;
                    case drawTools.MouseMove:
                        mainPanelGraphics.DrawLine(drawPen, startPoint, new Point(X, Y));
                        theMemoryGraphics.DrawLine(drawPen, startPoint, new Point(X, Y));
                        startPoint.X = X;
                        startPoint.Y = Y;
                        break;
                    case drawTools.Line:
                        mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
                        mainPanelGraphics.DrawLine(new Pen(drawPen.Color, drawPen.Width), startPoint, new Point(X, Y));
                        break;
                    case drawTools.Rectangle:
                        //*******************************************
                        
                        float startX, startY, wide, height;
                        if (X > startPoint.X)
                        {
                            wide = X - startPoint.X;
                            startX = startPoint.X;
                        }
                        else
                        {
                            wide = startPoint.X - X;
                            startX = X;
                        }
                        if (Y > startPoint.Y)
                        {
                            height = Y - startPoint.Y;
                            startY = startPoint.Y;
                        }
                        else
                        {
                            height = startPoint.Y - Y;
                            startY = Y;
                        }
                        //********************************************
                        mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
                        mainPanelGraphics.DrawRectangle(new Pen(drawPen.Color, drawPen.Width), startX, startY, wide, height);
                        break;
                    case drawTools.Ellipse:
                        mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
                        mainPanelGraphics.DrawEllipse(new Pen(drawPen.Color, drawPen.Width), startPoint.X, startPoint.Y, X - startPoint.X, Y - startPoint.Y);
                        break;
                    case drawTools.SolidEllipse:
                        break;
                    case drawTools.MultiEllipse:
                        mainPanelGraphics.DrawEllipse(new Pen(drawPen.Color, 1), startPoint.X, startPoint.Y, X - startPoint.X, Y - startPoint.Y);
                        theMemoryGraphics.DrawEllipse(new Pen(drawPen.Color, 1), startPoint.X, startPoint.Y, X - startPoint.X, Y - startPoint.Y);
                        break;
                    default:
                        break;
                }
            }
           if (SolidEllipseButton.Checked)
           {
               mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
               mainPanelGraphics.FillEllipse(drawBrush, startPoint.X, startPoint.Y, X - startPoint.X, Y - startPoint.Y);
           }

           if (UseEraserButton.Checked)
               EraserPic(X,Y);
        }

        protected void setPenColor(Color color)
        {
            drawPen.Color = color;
            PenStylepanel.Invalidate();
            drawBrush.Color = drawPen.Color;
        }

        protected Color MyConvertToColor(string color)
        {
            ColorConverter wcc = new ColorConverter();
           return  (Color)wcc.ConvertFromString(color);
        }

        protected string MyColorToConvert(Color color)
        {
            ColorConverter cc = new ColorConverter();
            return cc.ConvertToString(color);
        }
        protected void EraserPic(int X,int Y)
        {
            mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
            mainPanelGraphics.DrawLine(eraserPen, startPoint, new Point(X, Y));
            theMemoryGraphics.DrawLine(eraserPen, startPoint, new Point(X, Y));
            startPoint.X = X;
            startPoint.Y = Y;
        }
        //根据接收的消息判断画图
        protected void MessagePic(string coord)
        {
            int i = 0;
            while(coord.Substring(i,1) != ",")
            {
                i++;
            }
            int x = Int32.Parse(coord.Substring(0, i-1));
            int y = Int32.Parse(coord.Substring(i + 1, coord.Length - (i + 1)));
            PaintPic(x, y);
        }
        /// <summary>
        /// 消息处理
        /// </summary>
        /// <param name="m"></param>
        protected override void DefWndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case MessageType.BTN_SENDFILE:
                    OnSendFile(Marshal.PtrToStringAnsi(m.LParam));//如果检测到消息传到响应函数去
                    break;
                case MessageType.BTN_PEN:
                    UsePenButton_CheckedChanged(null, null);
                    break;
                case MessageType.BTN_ERASER:
                    UseEraserButton_CheckedChanged(null, null);
                    break;
                case MessageType.BTN_RANDOMPEN:
                    MouseMoveButton_CheckedChanged(null, null);
                    break;
                case MessageType.BTN_ROUND:
                    EllipseButton_CheckedChanged(null, null);
                    break;
                case MessageType.BTN_LINE:
                    LineButton_CheckedChanged(null, null);
                    break;
                case MessageType.BTN_SOLIDROUND:
                    SolidEllipseButton_CheckedChanged(null, null);
                    break;
                case MessageType.BTN_RECT:
                    RectangleButton_CheckedChanged(null, null);
                    break;
                case MessageType.BTN_MULTIROUND:
                    MultiEllipseButton_CheckedChanged(null, null);
                    break;
                case MessageType.PAT_XY:
                    MessagePic(Marshal.PtrToStringAnsi(m.LParam));
                    break;
                case MessageType.PAT_COLOR:
                    setPenColor(MyConvertToColor(Marshal.PtrToStringAnsi(m.LParam)));
                    break;
                case MessageType.BTN_OPENPANEL:
                    TurnOnPanel();
                    break;
                case MessageType.BTN_CLOSEPANEL:
                    TurnOffPanel();
                    break;
                case MessageType.MSG_STR:
                    MessageStr(Marshal.PtrToStringAnsi(m.LParam));
                    break;
                default:
                    base.DefWndProc(ref m);
                    break;
            }
            
        }

        protected void OnSendFile(string param)
        {
            
            
            switch (param)
            {
                  case "STARTSEND":
                          MessageImport.PostMessage(hMainFormHandle, 
                              MessageType.BTN_SENDFILEDATA, 
                              0, 
                              this.Handle);
                    break;
                default:
                    string status = param.Substring(0,8);
                    if (status == "确定接收文件吗?")
                    {
                        
                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    if (DialogResult.OK == MessageBox.Show("确定接收文件吗?", " ", MessageBoxButtons.OKCancel))
                        if (DialogResult.OK == fbd.ShowDialog())
                        {
                            filename = param.Substring(8, param.Length - 8);
                            FileStoreDirectory = fbd.SelectedPath;
                            MessageImport.PostMessage(
                            hMainFormHandle,
                            MessageType.BTN_RECEIVEDATA,
                            0,
                            this.Handle);
                            DataTransfer.send(DestinationIP, MessageType.BTN_SENDFILE, "STARTSEND");
                        }
                        }
                    break;
            }
        }


        public void TurnOnPanel()
        {
            //***************************************
            //
            this.Height = 468;
            this.Width = 507;
            //***************************************
            //
            this.MyHeadpictureBox.Show();
            this.OtherHeadpictureBox.Show();
            this.OtherInforichTextBox.Show();
            this.MyIDlabel.Show();
            this.MyIPlabel.Show();
            //***************************************
            //
            this.OpenBitmapbutton.Hide();
            this.CleanBitmapbutton.Hide();
            this.SaveBitmapbutton.Hide();
            this.Mainpanel.Hide();
            this.UsePenButton.Hide();
            this.UseEraserButton.Hide();
            this.PenColorCtrbutton.Hide();
            this.PenWideCtrgroupBox.Hide();
            this.PenStylegroupBox.Hide();
            this.PenWideCtrtrackBar.Hide();
            this.PenStylepanel.Hide();
            this.JustgroupBox.Hide();
            this.PenWidegroupBox.Hide();
            //***************************************
            //
            this.PaletteCtrbutton.Text = "打开即时画板";
            PaletteIsOpen = false;
            theMemoryGraphics.Clear(Color.White);
            //***************************************
        }

        public void TurnOffPanel()
        {
            //***************************************
            //
            this.Height = 468;
            this.Width = 675;
            //***************************************
            //
            this.MyHeadpictureBox.Hide();
            this.OtherHeadpictureBox.Hide();
            this.OtherInforichTextBox.Hide();
            this.MyIDlabel.Hide();
            this.MyIPlabel.Hide();
            //***************************************
            //
            this.OpenBitmapbutton.Show();
            this.CleanBitmapbutton.Show();
            this.SaveBitmapbutton.Show();
            this.Mainpanel.Show();
            this.UsePenButton.Show();
            this.UseEraserButton.Show();
            this.PenColorCtrbutton.Show();
            this.PenWideCtrgroupBox.Show();
            this.PenStylegroupBox.Show();
            this.PenWideCtrtrackBar.Show();
            this.PenStylepanel.Show();
            this.JustgroupBox.Show();
            this.PenWidegroupBox.Show();
            //***************************************
            //
            this.PaletteCtrbutton.Text = "关闭即时画板";
            PaletteIsOpen = true;
            theMemoryGraphics.Clear(Color.White);
            UsePenButton.Select();
            MouseMoveButton.Select();
            //***************************************
            //发送打开画板请求到对方客户端

        }
            //////////////////////////////////////////////////////////////////////////
            //FORM METHODS
            //////////////////////////////////////////////////////////////////////////
        public SessionForm(IntPtr handle,string IPaddress)//IntPtr用来传递主窗口的句柄
        {
            InitializeComponent();
            //*******************************************
            //
            if (SetForm.afterset == true)
            {
                this.BackColor = SetForm.FormBackColor;
                MyHeadpictureBox.BackgroundImage = SetForm.MyHeadImage;
            }
            //获取MAINFORM的句柄
            hMainFormHandle = handle;
            DestinationIP = IPaddress;
            //*******************************************
        }

        //************************************************
        //
        [DllImport("user32.dll")]
        //
        public static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
        //************************************************

        private void PaletteCtrbutton_Click(object sender, EventArgs e)
        {
            if (PaletteIsOpen == true)
            {
                TurnOnPanel();
                //发送消息到对方窗口通知关闭
                DataTransfer.send(DestinationIP, MessageType.BTN_OPENPANEL, null);
            }
            else
            {
                TurnOffPanel();
                DataTransfer.send(DestinationIP, MessageType.BTN_CLOSEPANEL, null);
            }
        }

        private void SessionForm_Load(object sender, EventArgs e)
        {
            //********************************************
            //
            AnimateWindow(this.Handle, 500, 21);
            //********************************************
            //初始化套接字
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            LAB_IP.Text = DestinationIP;
           
            //
            theMemoryImage = new Bitmap(Mainpanel.ClientRectangle.Width, Mainpanel.ClientRectangle.Height);
            theMemoryGraphics = Graphics.FromImage(theMemoryImage);
            theMemoryGraphics.FillRectangle(creatTheMemoryImagebrush, Mainpanel.ClientRectangle);
            mainPanelGraphics = Graphics.FromHdcInternal(Mainpanel.CreateGraphics().GetHdc());
            //********************************************
        }

        private void OpenBitmapbutton_Click(object sender, EventArgs e)
        {
            //********************************************
            //
            openBitmapDialog.InitialDirectory = "d:\\";
            openBitmapDialog.Filter = "Image Files(*.bmp;*.wmf;*.ico;*.cur;*.jgp)|*.bmp;*.wmf;*.ico;*.cur;*.jpg";
            if (openBitmapDialog.ShowDialog() == DialogResult.OK)
            {
                openFileImage = Image.FromFile(openBitmapDialog.FileName);
                theMemoryGraphics.DrawImage(openFileImage, Mainpanel.ClientRectangle);
            }
            mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
            //********************************************
          
        }

        private void SaveBitmapbutton_Click(object sender, EventArgs e)
        {
            //********************************************
            //
            saveBitmapDialog.InitialDirectory = "d:\\";
            saveBitmapDialog.Filter = "图像(*.bmp)|*.bmp";
            if (saveBitmapDialog.ShowDialog() == DialogResult.OK)
            {
                theMemoryImage.Save(saveBitmapDialog.FileName, ImageFormat.Bmp);
            }
            mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
            //********************************************
        }

        private void PenStylepanel_Paint(object sender, PaintEventArgs e)
        {
            //********************************************
            //
            Graphics g = PenStylepanel.CreateGraphics();
            g.DrawLine(new Pen(drawPen.Color, PenWideCtrtrackBar.Value), 10, 10, 120, 10);
            //********************************************
        }

        private void PenColorCtrbutton_Click(object sender, EventArgs e)
        {
            //********************************************
            //
            if (penColorDialog.ShowDialog() == DialogResult.OK)
                setPenColor(penColorDialog.Color);
            //
          
            mainPanelGraphics.DrawImage(theMemoryImage, 0, 0);
            DataTransfer.send(DestinationIP, MessageType.PAT_COLOR, MyColorToConvert(penColorDialog.Color));
            //********************************************
        }

        private void PenWideCtrtrackBar_Scroll(object sender, EventArgs e)
        {
            //********************************************
            //
            PenWideCtrtrackBar.SetRange(0, 10);
            if (UsePenButton.Checked)
            {
                drawPen.Width = PenWideCtrtrackBar.Value;
            }
            else
            {
                eraserPen.Width = PenWideCtrtrackBar.Value;
            }
            PenStylepanel.Invalidate();

            //********************************************
        }

        private void CleanBitmapbutton_Click(object sender, EventArgs e)
        {
            //********************************************
            //
            mainPanelGraphics.Clear(Color.White);
            theMemoryGraphics.Clear(Color.White);
            //********************************************
        }

        private void Mainpanel_MouseDown(object sender, MouseEventArgs e)
        {
            //********************************************
            //
            if (MouseMoveButton.Checked)
            {
                drawtool = drawTools.MouseMove;
            }
            else if (LineButton.Checked)
            {
                drawtool = drawTools.Line;
            }
            else if (RectangleButton.Checked)
            {
                drawtool = drawTools.Rectangle;
            }
            else if (EllipseButton.Checked)
            {
                drawtool = drawTools.Ellipse;
            }
            else if (SolidEllipseButton.Checked)
            {
                drawtool = drawTools.SolidEllipse;
            }
            else if (MultiEllipseButton.Checked)
            {
                drawtool = drawTools.MultiEllipse;
            }
            else
                drawtool = drawTools.None;
            //*********************************************
            //
            startPoint = e.Location;
            //
            isdrawing = true;
            //*********************************************
        }

        private void Mainpanel_MouseUp(object sender, MouseEventArgs e)
        {
            //*********************************************
            //
            endPoint = e.Location;
            
            isdrawing = false;
            //*********************************************
            //
            switch (drawtool)
            {
                case drawTools.None:
                    break;
                case drawTools.MouseMove:
                    break;
                case drawTools.Line:
                    theMemoryGraphics.DrawLine(drawPen, startPoint, endPoint);
                    break;
                case drawTools.Rectangle:
                    //*******************************************
                    //
                    float startX, startY, wide, height;
                    if (e.X > startPoint.X)
                    {
                        wide = endPoint.X - startPoint.X;
                        startX = startPoint.X;
                    }
                    else
                    {
                        wide = startPoint.X - endPoint.X;
                        startX = endPoint.X;
                    }
                    if (e.Y > startPoint.Y)
                    {
                        height = endPoint.Y - startPoint.Y;
                        startY = startPoint.Y;
                    }
                    else
                    {
                        height = startPoint.Y - endPoint.Y;
                        startY = endPoint.Y;
                    }
                    //********************************************
                    theMemoryGraphics.DrawRectangle(drawPen, startX, startY, wide, height);
                    break;
                case drawTools.Ellipse:
                    theMemoryGraphics.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X - startPoint.X, endPoint.Y - startPoint.Y);
                    break;
                case drawTools.SolidEllipse:
                    theMemoryGraphics.FillEllipse(drawBrush, startPoint.X, startPoint.Y, endPoint.X - startPoint.X, endPoint.Y - startPoint.Y);
                    break;
                case drawTools.MultiEllipse:
                    break;
                default:
                    break;
            }
            //*********************************************
        }

        private void Mainpanel_Paint(object sender, PaintEventArgs e)
        {
            //*********************************************

        }

        private void Mainpanel_MouseMove(object sender, MouseEventArgs e)
        {
            //*********************************************
            //
            mainPanelGraphics = Mainpanel.CreateGraphics();
            drawBrush.Color = drawPen.Color;
            if (isdrawing == true)
            {
                PaintPic(e.X, e.Y);
                DataTransfer.send(DestinationIP, MessageType.PAT_XY, e.X.ToString() + "," + e.Y.ToString());
            }
            //**************************************************************
            //
            
            
            //**************************************************************
         
        }

        private void UsePenButton_CheckedChanged(object sender, EventArgs e)
        {
            //*******************************************************************
            //
            PenStylegroupBox.Enabled = true;
            PenWideCtrtrackBar.Value = (int)drawPen.Width;
            PenStylepanel.Invalidate();
            DataTransfer.send(DestinationIP, MessageType.BTN_PEN, null);
            //********************************************************************
        }

        private void UseEraserButton_CheckedChanged(object sender, EventArgs e)
        {
            //*******************************************************************
            //
            PenStylegroupBox.Enabled = false;
            PenWideCtrtrackBar.Value = (int)eraserPen.Width;
            PenStylepanel.Invalidate();
            DataTransfer.send(DestinationIP, MessageType.BTN_ERASER, null);
            //*******************************************************************
        }

        private void SendFilebutton_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                FilePath = this.openFileDialog.FileName;
                filename = this.openFileDialog.SafeFileName;
                string sendstr = "确定接收文件吗?"+filename;

                DataTransfer.send(DestinationIP, MessageType.BTN_SENDFILE, sendstr);

            }
        }
        private void ShareFilesbutton_Click(object sender, EventArgs e)
        {
            IPAddress hostAddress = Dns.GetHostEntry(LAB_IP.Text.Trim()).AddressList[0];
            IPEndPoint point = new IPEndPoint(hostAddress, 3721);
            fbt.ip = point;
            fbt.ShowDialog();

            
        }

        private void SendPicturebutton_Click(object sender, EventArgs e)
        {
            try
            {
                DataTransfer.send("172.30.19.161", MessageType.BTN_SENDFILE, "123");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            
            
        }

        private void ChatNotebutton_Click(object sender, EventArgs e)
        {

       
        }

        private void MouseMoveButton_CheckedChanged(object sender, EventArgs e)
        {
            //Add code here
            DataTransfer.send(DestinationIP, MessageType.BTN_RANDOMPEN, null);
        }

        private void EllipseButton_CheckedChanged(object sender, EventArgs e)
        {
            //Add code here
            DataTransfer.send(DestinationIP, MessageType.BTN_ROUND, null);
        }

        private void LineButton_CheckedChanged(object sender, EventArgs e)
        {
            //Add code here

            DataTransfer.send(DestinationIP, MessageType.BTN_LINE, null);
        }

        private void SolidEllipseButton_CheckedChanged(object sender, EventArgs e)
        {
            //Add code here
            DataTransfer.send(DestinationIP, MessageType.BTN_SOLIDROUND, null);
        }

        private void RectangleButton_CheckedChanged(object sender, EventArgs e)
        {
            //Add code here
            DataTransfer.send(DestinationIP, MessageType.BTN_RECT, null);
        }

        private void MultiEllipseButton_CheckedChanged(object sender, EventArgs e)
        {
            //Add code here
            DataTransfer.send(DestinationIP, MessageType.BTN_MULTIROUND, null);
        }

        //test dialog
        private void SendMessagebutton_Click(object sender, EventArgs e)
        {


            if (this.InputRichTextBox.Text!="")
            {
                string strHostName = Dns.GetHostName(); //得到本机的主机名

                IPHostEntry ipEntry = Dns.GetHostByName(strHostName); //取得本机IP

                string strAddr = ipEntry.AddressList[0].ToString();

                this.NoteRichTextBox.AppendText(strAddr + " <" + DateTime.Now.ToString() + ">: " + this.InputRichTextBox.Text + "\n");

                DataTransfer.send(DestinationIP, MessageType.MSG_STR, this.InputRichTextBox.Text);
            }

            else
            {
                MessageBox.Show("消息内容不能为空");
            }
            this.InputRichTextBox.Text = "";
 
        }
        protected void MessageStr(string str)
        {
            this.NoteRichTextBox.AppendText(DestinationIP + " <" + DateTime.Now.ToString() + ">: " + str + "\n");
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
